package com.hiyee.user.controller;

import com.hiyee.api.BaseController;
import com.hiyee.api.controller.user.PassportControllerApi;
import com.hiyee.enums.UserStatus;
import com.hiyee.grace.result.ResponseJsonResult;
import com.hiyee.grace.result.ResponseStatusEnum;
import com.hiyee.pojo.AppUser;
import com.hiyee.pojo.bo.RegisterLoginBO;
import com.hiyee.user.service.UserService;
import com.hiyee.utils.IPUtil;
import com.hiyee.utils.JsonUtils;
import com.hiyee.utils.SmsUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.util.UUID;

@RestController
public class PassportController extends BaseController implements PassportControllerApi {

    final static Logger logger = LoggerFactory.getLogger(PassportController.class);

    @Autowired
    SmsUtils smsUtils;
    @Autowired
    UserService userService;

    /**
     * 获取验证码
     *
     * @param mobile
     * @param request
     * @return
     */
    @Override
    public ResponseJsonResult getSmsCode(String mobile, HttpServletRequest request) {
        // 根据 IP 限制客户 60 秒内只能获取一次验证码
        String ip = IPUtil.getRequestIp(request);
        redisOperator.setnx60s(REDIS_KEY_MOBILE_SMS_CODE_LOCK + ip, mobile);
        // 生成随机数
        String random = (int)((Math.random() * 9 + 1) * 100000) + "";
        // boolean result = smsUtils.sendSmsCode(mobile, random); 暂时取消阿里云发短信，因为需要钱
        boolean result = true;
        if(result) {
            logger.debug("[发送验证码] 手机号：".concat(mobile).concat(",验证码：").concat(random));
            // 存入缓存
            redisOperator.set(REDIS_KEY_MOBILE_SMS_CODE + mobile, "123456", 60 * 5);
            return ResponseJsonResult.success();
        }
        return ResponseJsonResult.fail();
    }

    /**
     * 一键登录注册
     *
     * @param registerLoginBO
     * @param bindingResult
     * @return
     */
    @Override
    public Object login(RegisterLoginBO registerLoginBO, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) {
        // 参数验证
        if(bindingResult.hasErrors()) {
            return ResponseJsonResult.errorMap(this.getErrors(bindingResult));
        }
        // 验证短信验证码
        String redisSmsCode = redisOperator.get(REDIS_KEY_MOBILE_SMS_CODE + registerLoginBO.getMobile());
        if(StringUtils.isEmpty(registerLoginBO.getSmsCode()) || redisSmsCode == null || !redisSmsCode.equals(registerLoginBO.getSmsCode())) {
            return ResponseJsonResult.error(ResponseStatusEnum.SMS_CODE_ERROR);
        }

        // 查询数据库用户是否已注册
        AppUser appUser = userService.getByMobile(registerLoginBO.getMobile());
        if(appUser != null && appUser.getActiveStatus() == UserStatus.FROZEN.getValue()) {
            // 用户不为空，状态为已冻结
            return ResponseJsonResult.error(ResponseStatusEnum.USER_STATUS_FROZEN);
        } else if (appUser == null) {
            // 自动注册
            appUser = userService.createUser(registerLoginBO.getMobile());
        }

        // 保存用户分布式会话操作
        int userActiveStatus = appUser.getActiveStatus();
        if(userActiveStatus != UserStatus.FROZEN.getValue()) {
            // 保存 token 到 redis 中
            String uToken = UUID.randomUUID().toString();
            redisOperator.set(REDIS_KEY_USER_TOKEN + appUser.getId(), uToken);
            // 保存用户信息到 redis 中
            redisOperator.set(REDIS_KEY_USER_INFO + appUser.getId(), JsonUtils.objectToJson(appUser));

            // 保存 id 和 token 到 cookie
            setCookie(request, response, "utoken", uToken, COOKIE_LIFE_TIME);
            setCookie(request, response, "uid", appUser.getId(), COOKIE_LIFE_TIME);
        }

        // 删除 redis 短信验证码
        redisOperator.del(REDIS_KEY_MOBILE_SMS_CODE + registerLoginBO.getMobile());

        return ResponseJsonResult.success(userActiveStatus);
    }

    /**
     * 用户退出登录
     *
     * @param userId
     * @param request
     * @param response
     * @return
     */
    @Override
    public ResponseJsonResult logout(String userId, HttpServletRequest request, HttpServletResponse response) {
        redisOperator.del(REDIS_KEY_USER_TOKEN + userId);
        setCookie(request, response, "utoken", "", 0);
        setCookie(request, response, "uid", "", 0);

        return ResponseJsonResult.success();
    }
}
